<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class M_Enrollment extends MY_Model 
{

	private $enrollment_id;
	private $profile_id;
	private $level_id;
	
	public function enroll($data)
	{
		$sy = $this->c_sy;
		$gp = $this->c_gp;
		$level_id = $data['stud_glevel'];
		$gperiod = $gp->gp_id;
		$sy = $sy->id;
		
		if($this->save_profile($data))
		{
			if($this->enroll_new_student($data))
			{
				if($this->generate_fee_for_new($this->level_id,$this->enrollment_id,$gperiod,$sy,'new'))
				{
					//if($this->_check_enrollee_nationality($this->level_id,$this->enrollment_id))
					//{
						return (object)['stat'=>true,'message'=>'Successfully Added New Student'];
					//}else{
						//unable to generate foreign fees
						//return (object)['stat'=>false,'message'=>'Unable to generate foreign fees'];
					//}
				}else{
					//unable to generate fees
					return (object)['stat'=>false,'message'=>'Unable to generate fees for student'];
				}
			}else{
				//unable to save in enrollment table
				return (object)['stat'=>false,'message'=>'Unable to save enrollment'];
			}
		}else{
			//unable to save profile
			return (object)['stat'=>false,'message'=>'Error occured unable to save profile'];
		}
	}

	private function save_profile($data)
	{
		// pd($data);
		$CI =& get_instance();
		$CI->load->helper('misc');
		$dob = DateTime::createFromFormat('m/d/Y',$data['bdate']['month'].'/'.$data['bdate']['day'].'/'.$data['bdate']['year']);

		if($dob)
		{
			$dob = $dob->format('Y-m-d');
			$profile['age'] = age($dob);
		}else{
			$dob = '0000-00-00';
		}

		$profile['firstname'] = $data['stud_fname'];
		$profile['lastname'] = $data['stud_lname'];
		$profile['middlename'] = $data['stud_mname'];
		$profile['dob'] = $dob;
		$profile['gender'] = $data['stud_gender'];
		$profile['nationality'] = $data['stud_nat'];
		
		// pd($profile);
		$this->db->insert('profiles',$profile);
		$this->profile_id = $this->db->insert_id();
		$this->level_id = $data['stud_glevel'];

		return $this->db->affected_rows() >=1 ? TRUE : FALSE;

	}

	private function enroll_new_student($data)
	{
		$CI =& get_instance();
		$CI->load->library('idno_creator');
		$generated_studentid = $CI->idno_creator->generate_new_id_compressed($this->level_id);


		$sy = $this->c_sy;
		$enrollment['e_sy_from'] = $sy->sy_from;
		$enrollment['e_sy_to'] = $sy->sy_to;
		$enrollment['e_ay_id'] = $sy->id;
		$enrollment['e_profile_id'] = $this->profile_id;
		$enrollment['e_grade_level'] = $this->level_id;
		$enrollment['e_created_at'] = NOW;
		$enrollment['e_enrollee_type'] = 'new';
		$enrollment['charge_to'] = 'yes';
		$enrollment['moved_to'] = 'yes';
		$enrollment['registrar_approved'] = 1;
		$enrollment['e_student_id'] = $generated_studentid;
		$this->db->insert('enrollments',$enrollment);
		$this->enrollment_id = $this->db->insert_id();
		return $this->db->affected_rows() > 0 ? TRUE : FALSE;	
	}

	private function generate_fees($level_id,$enroll_id)
	{
		$l = $this->db->select('payment_group')->limit(1)->where('level_id',$level_id)->get('levels');
	
		if($l->num_rows() >= 1)
		{
			$payment_group_id = $l->row()->payment_group;
			if($payment_group_id !== 0)
			{
				$select = $this->db->where('group_id',$payment_group_id)
							       ->get('payment_group_fees');
			
				
				if($select->num_rows() >= 1)
				{
					foreach($select->result() as $k => $v)
					{
						if($v->fee_type == 'misc')
						{
							$student_fee[$k]['is_misc_fee'] = 1;
							$student_fee[$k]['is_cca_fee'] = 0;
							$student_fee[$k]['is_tuition_fee'] = 0;
						}elseif($v->fee_type == 'tuit')
						{
							$student_fee[$k]['is_tuition_fee'] = 1;
							$student_fee[$k]['is_cca_fee'] = 0;
							$student_fee[$k]['is_misc_fee'] = 0;
						
						}elseif($v->fee_type == 'cca')
						{
							$student_fee[$k]['is_cca_fee'] = 1;
							$student_fee[$k]['is_misc_fee'] = 0;
							$student_fee[$k]['is_tuition_fee'] = 0;
						}
						
						
						$student_fee[$k]['sef_enrollment_id'] = $enroll_id;
						$student_fee[$k]['sef_fee_name'] = $v->fee_name;
						$student_fee[$k]['sef_fee_rate'] = $v->fee_price;
						$student_fee[$k]['sef_schoolyear_id'] = $this->c_sy->id;
						$student_fee[$k]['sef_gperiod_id'] = $this->c_gp->gp_id;
						$student_fee[$k]['sef_created'] = NOW;

					}

						$this->db->insert_batch('student_enrollment_fees',$student_fee);
						return $this->db->affected_rows() > 0 ? TRUE : FALSE;	
				
				}else{
					return TRUE;
				}
			}else{
				return TRUE;
			}
		}else{
			return TRUE;
		}
	}

	private function generate_fee_for_new($level_id,$enroll_id,$gperiod,$sy,$e_stat)
	{
		$this->load->model('M_student_payment_record');
		
		$q = $this->db->select('id')
					  ->where('payment_mode_name','cash basis')
					  ->get('payment_modes');
		$payment_plan_id = $q->num_rows() >= 1 ? $q->row() : FALSE; 

			$data_schedule = array(
							 array(
							'sps_e_id' => $enroll_id,
							'sps_pm_id' => $payment_plan_id->id,
							'sps_month' => 'Registration',
							'sps_tuition' => 0.00,
							'sps_matri' => 0.00
							)
							);

			$this->db->delete('student_payment_schedules', array('sps_e_id' => $enroll_id)); 
			$this->db->insert_batch('student_payment_schedules', $data_schedule); 
			

				//set tuition fee and misc fee for the current level
				if($this->set_tuition_fees_set_for_current_level($level_id,$enroll_id,$gperiod,$sy,$e_stat) == TRUE)
				{
					return TRUE;
				}else{
					log_message('error','unable to set fees for current level id '.$enroll_id);
					return FALSE;
				}
	}
	
	public function set_tuition_fees_set_for_current_level($level_id,$enroll_id,$gperiod,$sy,$e_stat)
	{
		/*
			Selects all tuition fee that is active.
		*/
		$this->load->model('M_student_payment_record');
		
		$c_spr_id = $this->M_student_payment_record->current_payment_record_id($enroll_id);
		
		$sql = "SELECT f.fee_name,f.fee_rate
				FROM fees f 
				WHERE f.is_tuition_fee = 1
				AND f.grade_level = ?
				AND f.ay_id = ?
				AND f.fee_stat = 'active'
				";
		if($e_stat=='old')
		{
			$sql .= " AND f.fee_old = 'yes'";
		}else{
			$sql .= " AND f.fee_new = 'yes'";
		}	
		$query = $this->db->query($sql,array($level_id,$sy));
		$data = $query->num_rows() >= 1 ? $query->result() : FALSE;
		
		//format tuition fees for entry
		if(!empty($data))
		{
			$count = 0;
			foreach($data as $fees)
			{
				$s_e_fees[$count]['sef_enrollment_id'] =$enroll_id;
				$s_e_fees[$count]['sef_fee_name'] = $fees->fee_name;
				$s_e_fees[$count]['sef_fee_rate'] = $fees->fee_rate;
				$s_e_fees[$count]['sef_gperiod_id'] = $gperiod;
				$s_e_fees[$count]['sef_schoolyear_id'] = $sy;
				$s_e_fees[$count]['sef_created'] = NOW;
				$s_e_fees[$count]['is_tuition_fee'] = 1;
				
				if($c_spr_id !== NULL)
				{
					$for_pb[$counter]['spb_fee_name'] = $fees->fee_name;
					$for_pb[$counter]['spb_remaining_balance'] = $fees->fee_rate;
					$for_pb[$counter]['spb_fee_rate'] = $fees->fee_rate;
					$for_pb[$counter]['spb_transacted_by'] =$this->CI->session->userdata('userid');
					$for_pb[$counter]['spb_spr_id'] =$c_spr_id;
					$for_pb[$counter]['spb_created'] =NOW;
					$for_pb[$counter]['spb_stud_enrollment_id'] = $enroll_id;
					$for_pb[$counter]['is_tuition_fee'] = 1;
				}
				
				$count++;
			}
			foreach($data as $fees){
			$data_tuit['sps_tuition'] = $fees->fee_rate;
			}
			$this->db->where('sps_e_id', $enroll_id);
			$this->db->update('student_payment_schedules', $data_tuit);

			//insert tuition fees
			$this->db->insert_batch('student_enrollment_fees',$s_e_fees);
			if(isset($for_pb) && !empty($for_pb)){
			$this->db->insert_batch('student_payment_breakdown',$for_pb);
			}
			/*
				if successfully inserted tuition fee
				call method insert_miscellaneous_fee()
				this method will insert misc fee for the student
			*/
			if($this->db->affected_rows() >= 1 )
			{
				//call method to insert misc fee
				if($this->_insert_miscellaneous_fee($enroll_id,$sy,$level_id,$e_stat) == TRUE)
				{
					return TRUE;
				}else{
					log_message('error','Unable to insert Miscellaneous fees. ID'.$enroll_id);
					return TRUE;
				}
			}else{
				log_message('error','Unable to insert Tuition fees. ID'.$enroll_id);
				return TRUE;
			}
		}else{
			log_message('error','No data for Tuition fees yet. ID'.$enroll_id);
			return TRUE;
		}
	}
	
	private function _insert_miscellaneous_fee($enroll_id,$sy,$level_id,$e_stat)
	{
		$this->load->model('M_student_payment_record');
		
		$c_spr_id = $this->M_student_payment_record->current_payment_record_id($enroll_id);
		
		$sql = "SELECT f.fee_name,f.fee_rate
				FROM fees f 
				WHERE f.is_misc_fee = 1
				AND f.grade_level = ?
				AND f.ay_id = ?
				AND f.fee_stat = 'active'
				";
		if($e_stat=='old')
		{
			$sql .= " AND f.fee_old = 'yes'";
		}else{
			$sql .= " AND f.fee_new = 'yes'";
		}	
				
		$query = $this->db->query($sql,array($level_id,$sy));
		$data = $query->num_rows() >= 1 ? $query->result() : FALSE;
		
		if(!empty($data))
		{
			$count = 0;
			foreach($data as $fees){
				$s_e_fees[$count]['sef_enrollment_id'] =$enroll_id;
				$s_e_fees[$count]['sef_fee_name'] = $fees->fee_name;
				$s_e_fees[$count]['sef_fee_rate'] = $fees->fee_rate;
				$s_e_fees[$count]['sef_schoolyear_id'] = $sy;
				$s_e_fees[$count]['sef_created'] = NOW;
				$s_e_fees[$count]['is_misc_fee'] = 1;
				
				if($c_spr_id !== NULL)
				{
					$for_pb[$counter]['spb_fee_name'] = $fees->fee_name;
					$for_pb[$counter]['spb_remaining_balance'] = $fees->fee_rate;
					$for_pb[$counter]['spb_fee_rate'] = $fees->fee_rate;
					$for_pb[$counter]['spb_transacted_by'] =$this->CI->session->userdata('userid');
					$for_pb[$counter]['spb_spr_id'] =$c_spr_id;
					$for_pb[$counter]['spb_created'] =NOW;
					$for_pb[$counter]['spb_stud_enrollment_id'] = $enroll_id;
					$for_pb[$counter]['is_misc_fee'] = 1;
				}
				
				$count++;
			}
			
			//insert tuition fees
			$this->db->insert_batch('student_enrollment_fees',$s_e_fees);
			if(isset($for_pb) && !empty($for_pb)){
			$this->db->insert_batch('student_payment_breakdown',$for_pb);
			}
			
			if($this->db->affected_rows() >= 1)
			{
				//call method to insert misc fee
				if($this->_insert_matriculation_fee($enroll_id,$sy,$level_id,$e_stat) == TRUE)
				{
					return TRUE;
				}else{
					log_message('error','Unable to insert Matriculation fees. ID'.$enroll_id);
					return TRUE;
				}
			}else{
				log_message('error','Unable to insert Miscellaneous fees. ID'.$enroll_id);
				return TRUE;
			}

		}else{
			log_message('error','No data Miscellaneous fees yet. ID'.$enroll_id);
			return TRUE;
		}
	}
	
	private function _insert_matriculation_fee($enroll_id,$sy,$level_id,$e_stat)
	{
		$this->load->model('M_student_payment_record');
		
		$c_spr_id = $this->M_student_payment_record->current_payment_record_id($enroll_id);
		
		$sql = "SELECT f.fee_name,f.fee_rate
				FROM fees f 
				WHERE f.is_cca_fee = 1
				AND f.grade_level = ?
				AND f.ay_id = ?
				AND f.fee_stat = 'active'
				";
		if($e_stat=='old')
		{
			$sql .= " AND f.fee_old = 'yes'";
		}else{
			$sql .= " AND f.fee_new = 'yes'";
		}	
		$query = $this->db->query($sql,array($level_id,$sy));
		$data = $query->num_rows() >= 1 ? $query->result() : FALSE;
		
		if(!empty($data))
		{
			$count = 0;
			foreach($data as $fees){
				$s_e_fees[$count]['sef_enrollment_id'] =$enroll_id;
				$s_e_fees[$count]['sef_fee_name'] = $fees->fee_name;
				$s_e_fees[$count]['sef_fee_rate'] = $fees->fee_rate;
				$s_e_fees[$count]['sef_schoolyear_id'] = $sy;
				$s_e_fees[$count]['sef_created'] = NOW;
				$s_e_fees[$count]['is_cca_fee'] = 1;
				
				if($c_spr_id !== NULL)
				{
					$for_pb[$counter]['spb_fee_name'] = $fees->fee_name;
					$for_pb[$counter]['spb_remaining_balance'] = $fees->fee_rate;
					$for_pb[$counter]['spb_fee_rate'] = $fees->fee_rate;
					$for_pb[$counter]['spb_transacted_by'] =$this->CI->session->userdata('userid');
					$for_pb[$counter]['spb_spr_id'] =$c_spr_id;
					$for_pb[$counter]['spb_created'] =NOW;
					$for_pb[$counter]['spb_stud_enrollment_id'] = $enroll_id;
					$for_pb[$counter]['is_cca_fee'] = 1;
				}
				
				$count++;
			}
			
			foreach($data as $fees){
			$data_matri['sps_matri'] = $fees->fee_rate;
			}
			$this->db->where('sps_e_id', $enroll_id);
			$this->db->update('student_payment_schedules', $data_matri);

			//insert tuition fees
			$this->db->insert_batch('student_enrollment_fees',$s_e_fees);
			if(isset($for_pb) && !empty($for_pb)){
			$this->db->insert_batch('student_payment_breakdown',$for_pb);
			}
			
			if($this->db->affected_rows() >= 1)
			{
				return TRUE;
			}else{
				log_message('error','Unable to insert Matriculation fees. ID'.$enroll_id);
				return TRUE;
			}

		}else{
			log_message('error','No data Matriculation fees yet. ID'.$enroll_id);
			return TRUE;
		}
	}
	
	/*check if foreigner then apply necessary fees*/
	private function _check_enrollee_nationality($lid,$eid)
	{
		// get enrolee nationality
		$q = $this->db->select('nationality')
				 ->join('enrollments e','e.e_profile_id = p.profile_id')
				 ->where('e_id',$eid)
				 ->limit(1)
				 ->get('profiles p');
		
		
		if($q->num_rows() >=1 )
		{
			$nat= $q->row()->nationality;		
				
			//if nationality is filipino no foreign fee applied
			if(strtolower($nat) == 'filipino')
			{
				return TRUE;
			}else{
				//get and insert foreign fees
				$ff = 'INSERT INTO student_enrollment_fees (sef_enrollment_id,
															sef_fee_name,
															sef_fee_rate,
															sef_gperiod_id,
															sef_schoolyear_id,
															is_elective_fee
															)
						SELECT ?,ff.fee_name,ff.fee_rate,?,?,1
						FROM foreign_fee ff
						WHERE ff.level_id = ?';
				
				$this->db->query($ff,array($eid,$this->c_gp->gp_id,$this->c_sy->id,$lid));
				
				return TRUE;
			}
		}else{
			return TRUE;
		}
	}
	
	public function _check_duplicate($p_id=FALSE)
	{
		$sy = $this->o_sy;
		$ay_id = $sy->id;
		
		if($p_id)
		{
			$q = $this->db->select('e_id')
						  ->where('e_profile_id',$p_id)
						  ->where('e_ay_id',$ay_id)
						  ->get('enrollments');
			
			return $q->num_rows() >=1 ? TRUE : FALSE;

		}else{
			return FALSE;
		}
	}
	
	public function early_enroll($e_id=FALSE,$l_id=FALSE,$p_id=FALSE)
	{
		if($e_id && $l_id && $p_id)
		{
			if($this->_check_duplicate($p_id) === FALSE)
			{	
				$q = $this->db->select('registrar_approved,guidance_approved,e_student_id')
						  ->where('e_profile_id',$p_id)
						  ->where('e_id',$e_id)
						  ->get('enrollments');
				$s = $q->row();		  

				$sy = $this->o_sy;
				$enrollment['e_sy_from'] = $sy->sy_from;
				$enrollment['e_sy_to'] = $sy->sy_to;
				$enrollment['e_ay_id'] = $sy->id;
				$enrollment['e_profile_id'] = $p_id;
				$enrollment['e_grade_level'] = $l_id;
				$enrollment['e_created_at'] = NOW;
				$enrollment['e_enrollee_type'] = 'old';
				$enrollment['registrar_approved'] = $s->registrar_approved;
				$enrollment['guidance_approved'] = $s->guidance_approved;
				$enrollment['e_student_id'] = $s->e_student_id;
				$this->db->insert('enrollments',$enrollment);
				$this->enrollment_id = $this->db->insert_id();
				return $this->db->affected_rows() > 0 ? TRUE : FALSE;
			}else{
				return FALSE;
			}
		}else{
			return FALSE;
		}
	}
}

/* End of file m_Enrollment.php */
/* Location: ./application/models/m_Enrollment.php */